{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 数据集\n",
    "- MovieLens 1M数据集\n",
    "> GroupLens Research（http://www.grouplens.org/node/73）采集了一\n",
    "组从20世纪90年末到21世纪初由MovieLens用户提供的电影评分数\n",
    "据。这些数据中包括电影评分、电影元数据（风格类型和年代）以及关\n",
    "于用户的人口统计学数据（年龄、邮编、性别和职业等）。基于机器学习\n",
    "算法的推荐系统一般都会对此类数据感兴趣。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- [1880-2010年间全美婴儿姓名-->获取](http://www.ssa.gov/oact/babynames/limits.html?)\n",
    "> 你可以用这个数据集做很多事，例如：\n",
    "·计算指定名字（可以是你自己的，也可以是别人的）的年度比例。\n",
    "·计算某个名字的相对排名。\n",
    "·计算各年度最流行的名字，以及增长或减少最快的名字。\n",
    "·分析名字趋势：元音、辅音、长度、总体多样性、拼写变化、首尾\n",
    "字母等。\n",
    "·分析外源性趋势：圣经中的名字、名人、人口结构变化等\n",
    "\n",
    "若链接失效，下载\"National data\"文件names.zip，解压后的目录中含有一组\n",
    "文件（如yob1880.txt）。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Ipython用法\n",
    "##### 对象内省\n",
    "- 若你不清楚某个变量或某个函数，可以在变量后加个问号（？），运行查看。如下"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "a=[1,2,3]\n",
    "\n",
    "a?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### 运行a？\n",
    "```\n",
    "Type:        list\n",
    "String form: [1, 2, 3]\n",
    "Length:      3\n",
    "Docstring:  \n",
    "list() -> new empty list\n",
    "list(iterable) -> new list initialized from iterable's items\n",
    "```\n",
    "\n",
    "- 若是函数或方法，可查看函数或方法的注释说明，如下"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n"
     ]
    }
   ],
   "source": [
    "def add(a,b):\n",
    "    \"\"\"\n",
    "    add a,b;\n",
    "    a+b->[a];\n",
    "    return a\n",
    "    \"\"\"\n",
    "    a=a+b\n",
    "    return a\n",
    "\n",
    "a=add(1,2)\n",
    "print(a)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### 运行add?，结果如下\n",
    "```\n",
    "Signature: add(a, b)\n",
    "Docstring:\n",
    "add a,b;\n",
    "a+b->[a];\n",
    "return a\n",
    "File:      c:\\windows\\system32\\0000python数据分析专题\\<ipython-input-14-cf3e265e3a8c>\n",
    "Type:      function\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "###### **??**可以查看函数或方法的源代码，如下\n",
    "> add??\n",
    "\n",
    "```\n",
    "Signature: add(a, b)\n",
    "Source:   \n",
    "def add(a,b):\n",
    "    \"\"\"\n",
    "    add a,b;\n",
    "    a+b->[a];\n",
    "    return a\n",
    "    \"\"\"\n",
    "    a=a+b\n",
    "    return a\n",
    "File:      c:\\windows\\system32\\0000python数据分析专题\\<ipython-input-14-cf3e265e3a8c>\n",
    "Type:      function\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 几个常用的魔法命令\n",
    "- **%hist**打印所有输入历史\n",
    "- **%logstart**记录控制台日志\n",
    "- **%run**加脚本名，可运行该文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Wall time: 20 ms\n"
     ]
    }
   ],
   "source": [
    "strings = ['foo', 'foobar', 'baz', 'qux', 'python', 'Guido Van Rossum']*11111\n",
    "%time method1 = [x for x in strings if x.startswith('foo')]\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 元组和列表的一些骚操作\n",
    "\n",
    "- tuple不可变，但tuple内的元素可变时，表象可变，但本质不变（元素是什么就是什么，不可能凭空删除、增加或是列表变成了字符串之类的）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(1, 2, 3)\n",
      "(1, 2, 3, [4, 5])\n",
      "(1, 2, 3, [4, 5, 6])\n",
      "('h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n')\n"
     ]
    }
   ],
   "source": [
    "tup=1,2,3\n",
    "print(tup)\n",
    "# 像（1.所提及\n",
    "tup=(1,2,3,[4,5,])\n",
    "print(tup)               #切片操作要会\n",
    "tup[3].append(6)\n",
    "print(tup)\n",
    "\n",
    "tup=tuple('hello python')\n",
    "print(tup)#注意空格也包含在内"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- **\\*** 的多面性\n",
    "    1. 能把list，tuple，string复制多份\n",
    "    2. 代指list、tuple、string中的一部分--->unpacking解包操作，如a，\\*b=（1,2,3），b=[2,3] (**注意b变成列表了**)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "too many values to unpack (expected 2)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-16-477797bc2f37>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      1\u001b[0m \u001b[0mLa\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m5\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mb\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mLa\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      3\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ma\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mb\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mValueError\u001b[0m: too many values to unpack (expected 2)"
     ]
    }
   ],
   "source": [
    "La=[1,2,3,4,5]\n",
    "a,b=La\n",
    "print(a,b)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 , [2, 3, 4, 5]\n",
      "1 , [2, 3, 4] , 5\n"
     ]
    }
   ],
   "source": [
    "La=[1,2,3,4,5]\n",
    "a,*b=La\n",
    "print(a,',',b)\n",
    "type(a)\n",
    "a,*b,c=La\n",
    "print(a,',',b,',',c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- list方法\n",
    "    1. append(b)--->末尾追加b\n",
    "    2. extend(list)--->合并列表，运算量比只用+小很多，不需要复制列表\n",
    "    3. insert(a,b)--->在指定索引a处插入b，计算量大，好比线性表删除元素要移动后面的其余元素\n",
    "    4. pop(a)  ---->删除索引a处元素并返回，默认a为-1\n",
    "    4. remove(b)--->删除指定的元素b，若b出现多次只删除最先出现的b\n",
    "    5. count(b)---->计算b出现的次数，tuple、string中都有用\n",
    "    6. index(obj)--->查找obj第一次出现的索引位置\n",
    "    7. clear()--->清空列表"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- Binary search and maintaining a sorted list （二分搜索和维持一个排好序的list）\n",
    "    ###### bisect模块\n",
    "    - bisect.bisect(),**找到插入位置**\n",
    "    - bisect.insort(),**实际插入元素**\n",
    "    - bisect不会去判断列表是否有序，需主观维护秩序\n",
    "    \n",
    "    ```import bisect\n",
    "c = [1, 2, 3, 4, 5]\n",
    "index=(bisect.bisect(c,2))\n",
    "print(index)\n",
    "c.insert(index,2)\n",
    "bisect.insort(c,3)\n",
    "print(c)\n",
    "输出：\n",
    "2\n",
    "[1, 2, 2, 3, 3, 4, 5]\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 一些内建函数\n",
    "- sorted（）（排序）\n",
    "- enumerate（）（枚举）\n",
    "- zip(), 用于\"pairs\"(成对)。把多个序列中每个对应的元素变成一对，最后返回一个含有tuple的list\n",
    "  > zip可以接收多个任意长度的序列，最后返回的结果取决于最短的序列\n",
    "- reversed(),翻转列表\n",
    "    > 注意，revered是一个generator（生成器，之后会详细讲），所以必须需要list来具现化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<zip object at 0x00000213031CDCC8>\n",
      "[('foo', 'one'), ('bar', 'two'), ('baz', '1three')]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[('foo', 'one', False), ('bar', 'two', True)]"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "seq1 = ['foo', 'bar', 'baz']\n",
    "seq2 = ['one', 'two', 'three']\n",
    "seq3 = [False, True]\n",
    "print(zip(seq1,seq2))\n",
    "print(list(zip(seq1,seq2)))\n",
    "list(zip(seq1, seq2, seq3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### dict字典（hash map）\n",
    "#### 注意点\n",
    "\n",
    "- 键值对\n",
    "- in只用于判断**键**是否在dict里\n",
    "- 字典的删除`del dic[key]`(无返回值)或`dic.pop(key)`(返回所删除的value)\n",
    "- 字典合并dic.update（dic1）,不生成新字典"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1: 'a', 'c': 3}\n",
      "3\n",
      "{1: 'a'}\n"
     ]
    }
   ],
   "source": [
    "dic={1:'a',2:'b','c':3}\n",
    "del dic[2]\n",
    "print(dic)\n",
    "print(dic.pop('c'))\n",
    "print(dic)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{1: 'a', 2: 'b', 'b': 4, 'c': 3, 'd': 1, 'a': 0}\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "['a', 'b', 'c', 'd']"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "dic={1:'a',2:'b','b':4,'c':3}\n",
    "# print(type(dic.keys())) #迭代器\n",
    "# for i,j in zip(dic.keys(),dic.values()):\n",
    "#     print (i,j)\n",
    "dic1={'d':1,'a':0}\n",
    "dic.update(dic1)\n",
    "print(dic)\n",
    "#sorted(dic) 注意只有键值同等类型才能排序\n",
    "del dic[1]\n",
    "del dic[2]\n",
    "sorted(dic)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 集合set\n",
    "- 花括号，无序，无重复元素\n",
    "- 常用来去重\n",
    "- 集合的复合运算\n",
    "    1. 并集`a.union(b)`或`a|b`\n",
    "    2. 交集`a.intersection(b)`或`a&b`\n",
    "    3. 差集\n",
    "- set的元素必须是不可更改的。如果想要list一样的元素，只能变为tuple：\n",
    "- 子集`a.issubset(b)`,父集`b.issuperset(a)`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "True\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a={1,2,3}\n",
    "b={1,2,3,4,5}\n",
    "print(a.issubset(b))\n",
    "b.issuperset(a)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### （列表）推导式\n",
    "1. 列表推导式\n",
    "    ```\n",
    "    [expr for x in list if condition ]\n",
    "    等同于\n",
    "    result=[]\n",
    "    for x in list:\n",
    "        if condition:\n",
    "            result.append(x)\n",
    "    \n",
    "    ```\n",
    "2. 字典推导式\n",
    "    ```\n",
    "    {key_expr:value_expr for x in collection if condition}\n",
    "    ```\n",
    "3. 集合推导式\n",
    "    ```\n",
    "    {expr for value in collection if condition}\n",
    "    ```\n",
    "\n",
    "#### 嵌套列表表达式\n",
    "\n",
    "**形如**\n",
    "```\n",
    "all_data = [['John', 'Emily', 'Michael', 'Mary', 'Steven'], \n",
    "        ['Maria', 'Juan', 'Javier', 'Natalia', 'Pilar']]\n",
    "        \n",
    "[name for names in all_data for name in names if name.count('e')>1]\n",
    "```\n",
    "**注意：**for部分是根据嵌套的顺序来写的，从外层的loop到内层的loop。\n",
    "```\n",
    "等同于：\n",
    "list=[]\n",
    "for names in all_data:\n",
    "    for name in names:\n",
    "        if name.count('e')>1:\n",
    "            list.append(name)\n",
    "运行结果：['Steven']\n",
    "```\n",
    "\n",
    "列表表达式里再有一个列表表达式也是可以的，可以生成a list of lists：\n",
    "**形如：**\n",
    "```\n",
    "[[x for x in tup] for tup in some_tuples]\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['Steven']"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "all_data = [['John', 'Emily', 'Michael', 'Mary', 'Steven'], \n",
    "        ['Maria', 'Juan', 'Javier', 'Natalia', 'Pilar']]\n",
    "# list=[]\n",
    "# for names in all_data:\n",
    "#     for name in names:\n",
    "#         if name.count('e')>=1:\n",
    "#             list.append(name)\n",
    "# list\n",
    "[name for namees in all_data for name in namees if name.count('e')>1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[[1, 2, 3], [4, 5, 6]]"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "some_tuples=[(1,2,3),(4,5,6)]\n",
    "[[x for x in tuple]for tuple in some_tuples]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 函数注意事项\n",
    "1. 命名空间（描述变量作用范围），作用范围（分全局global和局部local）\n",
    "    - global关键字\n",
    "       ```\n",
    "       a=[]\n",
    "       def ceshi():\n",
    "           for i in range(11):\n",
    "               a.append(i)\n",
    "           return a\n",
    "       ```\n",
    "\n",
    "2. 多个返回值\n",
    "\n",
    " 实际上函数返回了一个tuple，再解压赋给接受值\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 1, 2, 3, 4]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[]"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a=[]\n",
    "def ceshi():\n",
    "    a=[]\n",
    "    for i in range(5):\n",
    "        a.append(i)\n",
    "    return a\n",
    "print(ceshi())\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[0, 1, 2, 3, 4]"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a=[]\n",
    "def ceshi():\n",
    "    global a\n",
    "    for i in range(5):\n",
    "        a.append(i)\n",
    "ceshi()\n",
    "a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1, 2, 3)"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def func():\n",
    "    a=1\n",
    "    b=2\n",
    "    c=3\n",
    "    return a,b,c\n",
    "a,b,c=func()\n",
    "func()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1 2 3\n"
     ]
    }
   ],
   "source": [
    "print(a,b,c)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 补充知识 re.sub（pattern, repl, string, count=0, flags=0）用于正则的替换\n",
    "- pattern是匹配项\n",
    "- repl（replacement）是替换项\n",
    "- string是待匹配字符串\n",
    "- count是替换次数，因为有的正则匹配不止匹配到一次\n",
    "- flags是匹配模式像re.S,re.I\n",
    "\n",
    "> 1).re.I(re.IGNORECASE): 忽略大小写 \n",
    "2).re.M(MULTILINE): 多行模式，改变’^’和’$’的行为  \n",
    "3).re.S(DOTALL): 点任意匹配模式，改变’.’的行为 \n",
    "4).re.L(LOCALE): 使预定字符类 \\w \\W \\b \\B \\s \\S 取决于当前区域设定  \n",
    "5).re.U(UNICODE): 使预定字符类 \\w \\W \\b \\B \\s \\S \\d \\D 取决于unicode定义的字符属性  \n",
    "6).re.X(VERBOSE): 详细模式。这个模式下正则表达式可以是多行，忽略空白字符，并可以加入注释"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "today-is-sunday,my-name-is-JosonLe\n",
      "today-is-sunday,my-name is JosonLe\n"
     ]
    }
   ],
   "source": [
    "import re\n",
    "text='today is sunday,my name is JosonLe'\n",
    "print(re.sub(r'\\s','-',text))\n",
    "print(re.sub(r'\\s','-',text,count=3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "### 文件操作\n",
    "\n",
    "注意打开文件的几种方式：**r**只读，**w**只写且文件不存在时新建一个，**a**把内容追加到已存在的文件中且文件不存在会新建一个，**b**以二进制方式读写文件（与r，w连用），**r\\+** 读写双模式，**x**只写且创建一个新文件，若文件已存在则写入错误，**t**默认模式，自动将编码转为unicode  \n",
    "真正用的多的无非是**r，w，r+，rb，wb**\n",
    "\n",
    "建议打开文件用with open，因为**文件打开了就要关闭**\n",
    "\n",
    "还有文件路径的相对和绝对两种路径  \n",
    "注意文件操作后指针位置的变化  \n",
    "## ???open()有enoding参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "ename": "SyntaxError",
     "evalue": "invalid character in identifier (<ipython-input-27-c67096cedbba>, line 1)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;36m  File \u001b[1;32m\"<ipython-input-27-c67096cedbba>\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m    with open('C:\\\\Users\\\\j\\\\Desktop\\\\test.txt','xt'，encoding='gb2312') as f:\u001b[0m\n\u001b[1;37m                                                            ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid character in identifier\n"
     ]
    }
   ],
   "source": [
    "with open('C:\\\\Users\\\\j\\\\Desktop\\\\test.txt','xt'，encoding='gb2312') as f:\n",
    "    f.writelines('abcdefg')\n",
    "    \n",
    "    line=[i for i in f.readlines() if len(i)>1]\n",
    "    \n",
    "line\n",
    "# ('a         asf afgdfg  a'+'\\n       ').strip()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### OK，正式开始和数据分析打交道了\n",
    "\n",
    "### Numpy ，import numpy as np\n",
    "**先来见识几个常见词语：**ndarray（N-dimensional Array object，(n)多维数组对象），shape（维度），dtype（Data Type数据类型），vectorization(向量化)，indexing（索引），slicing（切片）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.4501554 ,  0.04044795, -0.5056155 , -1.94675628],\n",
       "       [ 0.58540729,  1.20829688, -2.51390608, -2.00532374],\n",
       "       [-1.30916725,  0.25706637,  0.45057117,  0.08400591]])"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "data=np.random.randn(3,4) #生成随机数组，3行4列\n",
    "data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[  4.50155396   0.40447947  -5.05615501 -19.46756278]\n",
      " [  5.85407292  12.08296883 -25.13906083 -20.05323745]\n",
      " [-13.09167251   2.57066374   4.50571171   0.84005906]]\n",
      "[[ 0.90031079  0.08089589 -1.011231   -3.89351256]\n",
      " [ 1.17081458  2.41659377 -5.02781217 -4.01064749]\n",
      " [-2.6183345   0.51413275  0.90114234  0.16801181]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[ 0.4501554 ,  0.04044795, -0.5056155 , -1.94675628],\n",
       "       [ 0.58540729,  1.20829688, -2.51390608, -2.00532374],\n",
       "       [-1.30916725,  0.25706637,  0.45057117,  0.08400591]])"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print(data *10)\n",
    "print(data+data)\n",
    "data    #data并未改变"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 数组特征shape（维度，形状）和dtype（数据类型）\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(3, 4)"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data.shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dtype('float64')"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data.dtype"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**可通过reshape（a，b,d,...）改变维度**，可以多维，必须满足大小一样"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.4501554 ,  0.04044795, -0.5056155 ],\n",
       "       [-1.94675628,  0.58540729,  1.20829688],\n",
       "       [-2.51390608, -2.00532374, -1.30916725],\n",
       "       [ 0.25706637,  0.45057117,  0.08400591]])"
      ]
     },
     "execution_count": 39,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data.reshape(4,3)       #实际data并未变"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "ename": "ValueError",
     "evalue": "cannot reshape array of size 12 into shape (4,4)",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-40-7625d3b0d7b4>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mdata\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mreshape\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m4\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[1;31mValueError\u001b[0m: cannot reshape array of size 12 into shape (4,4)"
     ]
    }
   ],
   "source": [
    "data.reshape(4,4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.4501554 ,  0.04044795, -0.5056155 , -1.94675628],\n",
       "       [ 0.58540729,  1.20829688, -2.51390608, -2.00532374],\n",
       "       [-1.30916725,  0.25706637,  0.45057117,  0.08400591]])"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data     #data并未改变"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[ 0.4501554 ,  0.04044795, -0.5056155 ],\n",
       "        [-1.94675628,  0.58540729,  1.20829688]],\n",
       "\n",
       "       [[-2.51390608, -2.00532374, -1.30916725],\n",
       "        [ 0.25706637,  0.45057117,  0.08400591]]])"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data.reshape(2,2,3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**可通过astype来转换数据类型**  \n",
    "\n",
    "- np.int32\n",
    "- np.float64\n",
    "- np.string_\n",
    "- 转换失败会返回ValueError\n",
    "- 可用其他数组的类型直接来制定类型， arr1.astype(arr2.dtype)\n",
    "- astype会生成一个新数组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dtype('int32')"
      ]
     },
     "execution_count": 58,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data=np.array([1,2,3,4])\n",
    "data.dtype"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 1.,  2.,  3.,  4.])"
      ]
     },
     "execution_count": 64,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data.astype(np.float)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([b'1', b'2', b'3', b'4'],\n",
       "      dtype='|S11')"
      ]
     },
     "execution_count": 62,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data.astype(np.string_)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dtype('int32')"
      ]
     },
     "execution_count": 65,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data.dtype"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 创建n维数组，np.array()\n",
    "传入一个序列，通过array函数变为数组，如果是嵌套序列就是多维数组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 1.,  2.,  3.,  4.])"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr1=np.array([1.0,2.0,3.0,4])\n",
    "arr1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[1, 2, 3, 4],\n",
       "       [5, 6, 7, 8]])"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr2=np.array([[1,2,3,4],[5,6,7,8]])\n",
    "arr2"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "np.array会自动根据数据类型保存合适的dtype类型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dtype('int32')"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr2.dtype"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "dtype('float64')"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr1.dtype"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### zeros()，ones()快速创建零数组和一数组\n",
    "可以在一个元祖中指定shape，如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,  1.])"
      ]
     },
     "execution_count": 52,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.ones(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.,  0.,  0.,  0.],\n",
       "       [ 0.,  0.,  0.,  0.],\n",
       "       [ 0.,  0.,  0.,  0.]])"
      ]
     },
     "execution_count": 49,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.zeros((3,4))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[ 1.,  1.],\n",
       "        [ 1.,  1.],\n",
       "        [ 1.,  1.]],\n",
       "\n",
       "       [[ 1.,  1.],\n",
       "        [ 1.,  1.],\n",
       "        [ 1.,  1.]]])"
      ]
     },
     "execution_count": 53,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.ones((2,3,2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "利用np.empty()快速初始化一个数组，可指定形状，其返回值并不一定是0，但比zones更快"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.38932851],\n",
       "       [ 0.51616513]])"
      ]
     },
     "execution_count": 55,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.empty((2,1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "arange（start，end，(step)）数组版的range函数,和range函数用法类似"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([1, 3, 5, 7, 9])"
      ]
     },
     "execution_count": 56,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.arange(1,10,2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 72,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Help on function ndim in module numpy.core.fromnumeric:\n",
      "\n",
      "ndim(a)\n",
      "    Return the number of dimensions of an array.\n",
      "    \n",
      "    Parameters\n",
      "    ----------\n",
      "    a : array_like\n",
      "        Input array.  If it is not already an ndarray, a conversion is\n",
      "        attempted.\n",
      "    \n",
      "    Returns\n",
      "    -------\n",
      "    number_of_dimensions : int\n",
      "        The number of dimensions in `a`.  Scalars are zero-dimensional.\n",
      "    \n",
      "    See Also\n",
      "    --------\n",
      "    ndarray.ndim : equivalent method\n",
      "    shape : dimensions of array\n",
      "    ndarray.shape : dimensions of array\n",
      "    \n",
      "    Examples\n",
      "    --------\n",
      "    >>> np.ndim([[1,2,3],[4,5,6]])\n",
      "    2\n",
      "    >>> np.ndim(np.array([[1,2,3],[4,5,6]]))\n",
      "    2\n",
      "    >>> np.ndim(1)\n",
      "    0\n",
      "\n"
     ]
    }
   ],
   "source": [
    "help(np.ndim)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### arrary的运算\n",
    "**类似数组运算，是对应位置的元素间进行运算**  \n",
    "两个数组间的比较会产生布尔数组，如下："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 76,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1 2 3]\n",
      " [4 5 6]]\n",
      "[[0 3 5]\n",
      " [4 2 7]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[False,  True,  True],\n",
       "       [False, False,  True]], dtype=bool)"
      ]
     },
     "execution_count": 76,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr1=np.array([[1,2,3],[4,5,6]])\n",
    "arr2=np.array([[0,3,5],[4,2,7]])\n",
    "print(arr1)\n",
    "print(arr2)\n",
    "arr2>arr1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 索引和切片操作\n",
    "- 一维数组类似列表等索引和切片操作  \n",
    "\n",
    "**有几点需要注意，和列表等切片不一样**，见下列程序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'list'>\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[1, 2, 9, 6, 7, 8]"
      ]
     },
     "execution_count": 81,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "list=[1,2,3,4,5,6,7,8]\n",
    "print(type(list[2:5]))\n",
    "list[2:5]=[9]      #注意要赋值列表，这里是替换\n",
    "list"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'numpy.ndarray'>\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([0, 1, 9, 9, 9, 5, 6, 7, 8])"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr=np.arange(9)\n",
    "print(type(arr[2:5]))\n",
    "arr[2:5]=9      #这里的意思是对数组【2:5】重新复制9\n",
    "arr"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "> array的切片后的结果只是一个views（视图），用来代表原有array对应的元素，而不是创建了一个新的array。但list里的切片是产生了一个新的list.----摘自《利用Python进行数据分析 第二版》  \n",
    "之所以这样设计是出于性能和内存的考虑，毕竟如果总是复制数据的话，会很影响运算时间。当然如果想要复制，可以使用copy()方法，比如arr[5:8].copy()\n",
    "\n",
    "如下列程序所示："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([ 0,  1, 10,  9,  9,  5,  6,  7,  8])"
      ]
     },
     "execution_count": 87,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr2=arr[2:5]\n",
    "print(arr2[0])\n",
    "arr2[0]=10\n",
    "arr"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用**copy()**方法可以复制新生成一个数组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 0,  1, 10,  9,  9,  5,  6,  7,  8])"
      ]
     },
     "execution_count": 89,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr3=arr[2:5].copy()\n",
    "arr3[0]=9\n",
    "arr"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "- 多维度数组在索引和切片上略有区别，单看一个例子就能很快搞明白\n",
    "   OK，看看一个三维的数组"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[ 0,  1,  2],\n",
       "        [ 3,  4,  5]],\n",
       "\n",
       "       [[ 6,  7,  8],\n",
       "        [ 9, 10, 11]]])"
      ]
     },
     "execution_count": 92,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr=np.arange(12).reshape((2,2,3))\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0, 1, 2],\n",
       "       [3, 4, 5]])"
      ]
     },
     "execution_count": 94,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([0, 1, 2])"
      ]
     },
     "execution_count": 95,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr[0,0]  #等同于arr[0][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "5"
      ]
     },
     "execution_count": 97,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 等同于arr[0][1][2]\n",
    "arr[0,1,2]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[69, 69, 69],\n",
       "        [69, 69, 69]],\n",
       "\n",
       "       [[ 6,  7,  8],\n",
       "        [ 9, 10, 11]]])"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "arr=np.arange(12).reshape((2,2,3))\n",
    "arr1=arr[0].copy()\n",
    "arr[0]=69\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[ 0,  1,  2],\n",
       "        [ 3,  4,  5]],\n",
       "\n",
       "       [[ 6,  7,  8],\n",
       "        [ 9, 10, 11]]])"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr[0]=arr1\n",
    "arr"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "然后是切片操作，对于多维稍稍转个弯就好"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[[ 0,  1,  2],\n",
       "        [ 3,  4,  5],\n",
       "        [ 6,  7,  8]],\n",
       "\n",
       "       [[ 9, 10, 11],\n",
       "        [12, 13, 14],\n",
       "        [15, 16, 17]],\n",
       "\n",
       "       [[18, 19, 20],\n",
       "        [21, 22, 23],\n",
       "        [24, 25, 26]]])"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr=np.arange(27).reshape(3,3,3)\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[[ 9 10 11]\n",
      "  [12 13 14]\n",
      "  [15 16 17]]\n",
      "\n",
      " [[18 19 20]\n",
      "  [21 22 23]\n",
      "  [24 25 26]]]\n",
      "***\n",
      "[[[ 9 10 11]]\n",
      "\n",
      " [[18 19 20]]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([[[10]],\n",
       "\n",
       "       [[19]]])"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "print(arr[1:])   #实际上切片时可以把内层分成三个模块就可以看成一维数组，所以【1：】切下来后两个模块\n",
    "print('***')\n",
    "print(arr[1:,:1])#然后对每个模块而言又包含三个模块，所以【1：，：1】切下来每个模块第一个小模块\n",
    "arr[1:,:1,1:2]  #剩下的就是一维数组正常处理M"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "从上面可以看出，对多维数组的切片操作，每次都是**对行处理的（比如arr[1:]就是取后两行）**，简单明了吧"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 布尔型索引\n",
    "因为数组间可以比较，进而可以得到一个布尔类型数组，可用来作为索引\n",
    "```\n",
    "    import numpy as np\n",
    "    names=np.array(['Li','tom','Jack'])\n",
    "    scores=np.array([[1,2,3],[4,5,6],[7,8,9]])\n",
    "    print(names=='Jack')\n",
    "    scores[names=='Jack']          ---->做索引\n",
    "```\n",
    "结果得：\n",
    "```\n",
    "array([False, False,  True], dtype=bool)         ----->布尔型数组\n",
    "Out[10]: array([[7, 8, 9]])\n",
    "```\n",
    "\n",
    "能选择多个名字，做布尔运算，用‘&’‘|’  \n",
    "如`mask=(names==\"Li\")|(names=='tom')`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[False False  True]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "array([False, False,  True], dtype=bool)"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "names=np.array(['Li','tom','Jack'])\n",
    "scores=np.array([[1,2,3],[4,5,6],[7,8,9]])\n",
    "print(names=='Jack')\n",
    "scores[names=='Jack']\n",
    "names==\"Jack\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 花样索引\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "#### 数组转置和轴交换（不产生新数组）\n",
    "- 使用T属性\n",
    "- 使用transpose方法 ------>轴交换\n",
    "- 常用来做**矩阵乘法**,np.dot(A*,A)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0, 1, 2],\n",
       "       [3, 4, 5],\n",
       "       [6, 7, 8]])"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr=np.arange(9).reshape((3,3))\n",
    "arr"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[0, 3, 6],\n",
       "       [1, 4, 7],\n",
       "       [2, 5, 8]])"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "arr.T"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[45, 54, 63],\n",
       "       [54, 66, 78],\n",
       "       [63, 78, 93]])"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.dot(arr.T,arr)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "普通的二维矩阵多采用T属性，而多维数组一般使用transponse方法（轴交换）\n",
    "\n",
    "**先说明一个问题（用三维数组）**  \n",
    "[Python Numpy中transpose()函数的使用](http://www.cnblogs.com/chenyansu/p/6774963.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### OK，接下来我们进入Numpy函数部分\n",
    "- [为什么你用不好Numpy的random函数？](https://www.cnblogs.com/lemonbit/p/6864179.html)(转自博客园：http://www.cnblogs.com/lemonbit/)\n",
    "- np.random.rand()产生介于[ 0,1)的随机数据样本\n",
    "- np.random.randn()产生标准正态分布数据样本\n",
    "\n",
    "```\n",
    "import numpy as np\n",
    "np.random.rand(3,2,2)\n",
    "\n",
    "out[]:array([[[ 0.09925242,  0.36938598],\n",
    "        [ 0.88371184,  0.29185346]],\n",
    "\n",
    "       [[ 0.10140629,  0.56377258],\n",
    "        [ 0.46131379,  0.13071904]],\n",
    "\n",
    "       [[ 0.83257134,  0.47248255],\n",
    "        [ 0.31949308,  0.52340607]]])\n",
    "        \n",
    "```\n",
    "\n",
    "#### 处理数组形态\n",
    "\n",
    "- arr.reshape(),np.resize(arr,(new_shape))和np.ravel(arr)、np.flatten(arr),前者不说，后二者是多维数组一维化\n",
    "\n",
    "**区别在于：**ravel返回的是数组的view（视图），flatten(拷贝)生成了新数组；reshape是直接修改这个对象的，而resize则会生成一个新的对象\n",
    "\n",
    "```\n",
    "import numpy as np\n",
    "arr=np.arange(12).reshape((3,2,2))\n",
    "print(arr)\n",
    "b=np.ravel(arr)#等同于arr.ravel()\n",
    "c=arr.flatten()\n",
    "print('ravel后：')\n",
    "print(b)\n",
    "b[0]=666\n",
    "print('原arr:')\n",
    "print(arr)\n",
    "print('flatten后：')\n",
    "print(c)\n",
    "c[0]=999\n",
    "print('原arr:')\n",
    "print(arr)\n",
    "\n",
    "out[]:\n",
    "\n",
    "[[[ 0  1]\n",
    "  [ 2  3]]\n",
    "\n",
    " [[ 4  5]\n",
    "  [ 6  7]]\n",
    "\n",
    " [[ 8  9]\n",
    "  [10 11]]]\n",
    "ravel后：\n",
    "[ 0  1  2  3  4  5  6  7  8  9 10 11]\n",
    "原arr:\n",
    "[[[666   1]\n",
    "  [  2   3]]\n",
    "\n",
    " [[  4   5]\n",
    "  [  6   7]]\n",
    "\n",
    " [[  8   9]\n",
    "  [ 10  11]]]\n",
    "flatten后：\n",
    "[ 0  1  2  3  4  5  6  7  8  9 10 11]\n",
    "原arr:\n",
    "[[[666   1]\n",
    "  [  2   3]]\n",
    "\n",
    " [[  4   5]\n",
    "  [  6   7]]\n",
    "\n",
    " [[  8   9]\n",
    "  [ 10  11]]]\n",
    "\n",
    "```\n",
    "#### 数组叠加(前提要确保待叠加的行或列对齐)\n",
    "- np.hstack((a,b)),水平叠加：先介绍水平叠加方式，即用元组确定ndarrays数组的形状，然后交由hstack（）函数来码放这些数组。\n",
    "- np.vstack((a,b)),垂直叠加：使用垂直叠加方法时，先要构建一个元祖，然后将元祖交给vstack（）函数来码放数组。\n",
    "- np.concatenate((a,b),axis),axis=0实现垂直叠加；axis=1实现水平叠加\n",
    "- np.dstack((a,b)),深度叠加：这种方法是沿着第三个坐标轴（纵向）的方向来叠加一摞数组。举例来说，可以在一个图像数据的二维数组上叠加另一幅图像的数据。\n",
    "\n",
    "```\n",
    "import numpy as np\n",
    "a=np.arange(12).reshape((3,4))\n",
    "b=a*2\n",
    "c=np.hstack((a,b,a))\n",
    "d=np.vstack((a,b,a))\n",
    "np.concatenate((a,b),axis=0)\n",
    "np.concatenate((a,b),axis=1)\n",
    "e=np.dstack((a,b))\n",
    "```\n",
    "\n",
    "#### 数组拆分\n",
    "> 可以从纵向，横向和深度方向来拆分数组，相关函数有hsplit(),vsplit(),dsplit()和split()。我们即可以把数组分成相同的形状的数组，也可以从规定的位置开始切取数组。\n",
    "\n",
    "- np.hsplit( arr, n ) 或 np.split(arr, n ,axis=1)，横向拆分，沿arr横轴分解为n部分（保证横轴能够等n化，如6可以分成3,2部分，6和1无意义）\n",
    "\n",
    "\n",
    "```\n",
    "import numpy as np\n",
    "a=np.arange(27).reshape((3,9))\n",
    "print(a)\n",
    "np.hsplit(a,3)\n",
    "#np.split(a,3,axis=0)\n",
    "\n",
    "out[]:\n",
    "[[ 0  1  2  3  4  5  6  7  8]\n",
    " [ 9 10 11 12 13 14 15 16 17]\n",
    " [18 19 20 21 22 23 24 25 26]]\n",
    "Out[97]:\n",
    "[array([[ 0,  1,  2],\n",
    "        [ 9, 10, 11],\n",
    "        [18, 19, 20]]), array([[ 3,  4,  5],\n",
    "        [12, 13, 14],\n",
    "        [21, 22, 23]]), array([[ 6,  7,  8],\n",
    "        [15, 16, 17],\n",
    "        [24, 25, 26]])]\n",
    "```\n",
    "\n",
    "- np.vsplit( arr, n )或 np.split(arr, n axis=0), 纵向拆分，类似横向\n",
    "- np.dsplit(arr, n ),深向拆分,dsplit()函数会沿着深度方向分解数组。\n",
    "\n",
    "```\n",
    "import numpy as np\n",
    "a=np.arange(36).reshape((2,3,6))\n",
    "print('a:',a)\n",
    "np.dsplit(a,3)\n",
    "\n",
    "out[]:\n",
    "\n",
    "a:[[[ 0  1  2  3  4  5]\n",
    "  [ 6  7  8  9 10 11]\n",
    "  [12 13 14 15 16 17]]\n",
    "\n",
    " [[18 19 20 21 22 23]\n",
    "  [24 25 26 27 28 29]\n",
    "  [30 31 32 33 34 35]]]\n",
    "Out[107]:\n",
    "[array([[[ 0,  1],\n",
    "         [ 6,  7],\n",
    "         [12, 13]],\n",
    " \n",
    "        [[18, 19],\n",
    "         [24, 25],\n",
    "         [30, 31]]]), array([[[ 2,  3],\n",
    "         [ 8,  9],\n",
    "         [14, 15]],\n",
    " \n",
    "        [[20, 21],\n",
    "         [26, 27],\n",
    "         [32, 33]]]), array([[[ 4,  5],\n",
    "         [10, 11],\n",
    "         [16, 17]],\n",
    " \n",
    "        [[22, 23],\n",
    "         [28, 29],\n",
    "         [34, 35]]])]\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 108,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a: [[[ 0  1  2  3  4  5]\n",
      "  [ 6  7  8  9 10 11]\n",
      "  [12 13 14 15 16 17]]\n",
      "\n",
      " [[18 19 20 21 22 23]\n",
      "  [24 25 26 27 28 29]\n",
      "  [30 31 32 33 34 35]]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[array([[[ 0,  1],\n",
       "         [ 6,  7],\n",
       "         [12, 13]],\n",
       " \n",
       "        [[18, 19],\n",
       "         [24, 25],\n",
       "         [30, 31]]]), array([[[ 2,  3],\n",
       "         [ 8,  9],\n",
       "         [14, 15]],\n",
       " \n",
       "        [[20, 21],\n",
       "         [26, 27],\n",
       "         [32, 33]]]), array([[[ 4,  5],\n",
       "         [10, 11],\n",
       "         [16, 17]],\n",
       " \n",
       "        [[22, 23],\n",
       "         [28, 29],\n",
       "         [34, 35]]])]"
      ]
     },
     "execution_count": 108,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "a=np.arange(36).reshape((2,3,6))\n",
    "print('a:',a)\n",
    "np.dsplit(a,3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### np.meshgrid()和np.where()\n",
    "前者用于产生网格矩阵，后者一句话讲不清，[可参考这篇文章](http://www.cnblogs.com/sunshinewang/p/6897966.html)或[ python笔记之NUMPY中的meshgrid()——生成以某点为中心指定半径内的](http://blog.csdn.net/baoqian1993/article/details/52116164)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "### 文件读取\n",
    "- np.genfromtxt()[可参考这篇文章](http://blog.csdn.net/chang_yuan_2011/article/details/21300443)，[文档](https://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html)\n",
    "    - genfromtxt唯一的强制参数是数据的来源。它可以是一个对应于一个本地或远程文件的名字字符串,或一个有read方法的file-like对象(如一个实际的文件或StringIO。StringIO对象)。如果参数是一个远程文件的URL,后者在当前目录中自动下载。输入文件可以是一个文本文件或存档，目前,该函数识别gzip和bz2(bzip2)。归档文件的类型是检查文件的扩展：如果文件名以“.gz”结尾”,gzip存档;如果它结尾是“bz2”,bzip2存档。\n",
    "    - autostrip参数:当把一行分割成一个字符串序列，序列中的每一项前后的多余空格还存在，可以将autostrip参数设置为true，去掉空格。\n",
    "    - **comments参数:** 一个字符串,标志着一个注释的开始符号。默认是\"#\"，在转换过程中注释标记可能发生在任何地方。任何字符出现在在注释标记之后会被忽略。(**注意：这种行为有一个例外:如果可选的参数names= True,第一行检查到注释行会被认为是名称。**)\n",
    "    - **skip_header和skip_footer参数:** 一个文件的页眉会阻碍文件的处理。在这种情况下,我们需要使用skip_header可选参数。这个参数的值必须是一个整数,跳过文件开头的对应的行数,然后再执行任何其他操作。同样的,我们通过使用skip_footer属性和n的值可以跳过文件的最后n行。**默认值都为0.**\n",
    "    - **names参数：**可以将names参数设置为true并跳过第一行，程序将把第一行作为列名称，即使第一行被注释掉了也会被读取。或可以使用dtype设置名称，也可以重写names，默认的names是none，当names=none时，将有numpy产生一些标准默认的值\"f%i\",我们可以通过defaultfmt改变默认格式。\n",
    "    -  usercols参数： 在某些情况下,我们只对数据中的某些列感兴趣。我们可以使用usecols选择感兴趣的列。这个参数接受一个整数或一个整数序列作为索引。记住,按照惯例,第一列的索引0，-1对应最后一列。如果列有名称,我们也可以将usecols参数设置为他们的名称,或者包含列名称一个字符串序列或逗号分隔的字符串。\n",
    "    - delimiter参数是用来指定每一行用来分隔数据的分隔符,比如说csv逗号分隔符，有的会用分号‘;’\n",
    "    - dtype参数，我们从文件读取的字符串序列要转换为其他类型数据时需设置dtype参数。默认是float类型\n",
    "        - 注意：默认float时，无法转换成float类型的数据会输出nan（not a number），对于留空的数据则显示为na（not available）\n",
    "        > - 单个类型,如dtype =float。\n",
    "     - 一个序列类型，例如dtype=(int, float, float).\n",
    "     - 一个逗号分隔的字符串，例如dtype=\"i4,f8,|S3\".\n",
    "     - 一个字典包含两个键‘names’和‘formats’\n",
    "     - 一个元组序列，例如dtype = [('A',int),('B',float)]\n",
    "     - 一个存在的numpy.dtype对象\n",
    "     - 一个特殊的值None，在这种情况下，每个列的类型有自身数据决定。将参数设置成None效率较低。因为它会从布尔值开始检验，然后是整型，浮点型，复数最后是字符串，直到满足条件为止。\n",
    "    \n",
    "- np.loadtxt()类似genfromtxt，只不过genfromtxt更专业（面向结构化数据，可以处理缺失数据）\n",
    "- np.savetxt(),类似前两者的相反操作，把数组以某种分隔符写入文件"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[  7.4  ,   0.7  ,   0.   , ...,   0.56 ,   9.4  ,   5.   ],\n",
       "       [  7.8  ,   0.88 ,   0.   , ...,   0.68 ,   9.8  ,   5.   ],\n",
       "       [  7.8  ,   0.76 ,   0.04 , ...,   0.65 ,   9.8  ,   5.   ],\n",
       "       ..., \n",
       "       [  6.3  ,   0.51 ,   0.13 , ...,   0.75 ,  11.   ,   6.   ],\n",
       "       [  5.9  ,   0.645,   0.12 , ...,   0.71 ,  10.2  ,   5.   ],\n",
       "       [  6.   ,   0.31 ,   0.47 , ...,   0.66 ,  11.   ,   6.   ]])"
      ]
     },
     "execution_count": 28,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "#导入红酒相关数据\n",
    "wine_data=np.genfromtxt('C:\\\\Users\\\\j\\\\Desktop\\\\winequality.csv',delimiter=';',skip_header=1)\n",
    "\n",
    "#第一行参数\n",
    "#fixed acidity;\"volatile acidity\";\"citric acid\";\"residual sugar\";\"chlorides\";\"free sulfur dioxide\";\"total sulfur dioxide\";\"density\";\"pH\";\"sulphates\";\"alcohol\";\"quality\"\n",
    "#固定酸度;“挥发性酸”;“柠檬酸”;“剩余糖分”;“氯化物”;“自由二氧化硫”;“总二氧化硫”;“密度”;“pH”;“硫酸盐”;“酒精”;“质量”\n",
    "wine_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[  9.4,   5. ],\n",
       "       [  9.8,   5. ],\n",
       "       [  9.8,   5. ],\n",
       "       ..., \n",
       "       [ 11. ,   6. ],\n",
       "       [ 10.2,   5. ],\n",
       "       [ 11. ,   6. ]])"
      ]
     },
     "execution_count": 33,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "wine_data[:,-2:]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 7.4  ,  0.7  ,  5.   ],\n",
       "       [ 7.8  ,  0.88 ,  5.   ],\n",
       "       [ 7.8  ,  0.76 ,  5.   ],\n",
       "       ..., \n",
       "       [ 6.3  ,  0.51 ,  6.   ],\n",
       "       [ 5.9  ,  0.645,  5.   ],\n",
       "       [ 6.   ,  0.31 ,  6.   ]])"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "wine_data=np.genfromtxt('C:\\\\Users\\\\j\\\\Desktop\\\\winequality.csv',delimiter=';',skip_header=1,usecols=(0,1,-1))\n",
    "wine_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.   ,  0.   ,  0.   , ...,  0.   ,  0.   ,  0.   ],\n",
       "       [ 0.4  ,  0.18 ,  0.   , ...,  0.12 ,  0.4  ,  0.   ],\n",
       "       [ 0.4  ,  0.06 ,  0.04 , ...,  0.09 ,  0.4  ,  0.   ],\n",
       "       ..., \n",
       "       [-1.1  , -0.19 ,  0.13 , ...,  0.19 ,  1.6  ,  1.   ],\n",
       "       [-1.5  , -0.055,  0.12 , ...,  0.15 ,  0.8  ,  0.   ],\n",
       "       [-1.4  , -0.39 ,  0.47 , ...,  0.1  ,  1.6  ,  1.   ]])"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#将每一行与第一行比较\n",
    "wine_data-wine_data[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[  9.4,   5. ],\n",
       "       [  9.8,   5. ],\n",
       "       [  9.8,   5. ],\n",
       "       ..., \n",
       "       [ 11. ,   6. ],\n",
       "       [ 10.2,   5. ],\n",
       "       [ 11. ,   6. ]])"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#截取wine部分数据分析\n",
    "wine=wine_data[:,-2:]\n",
    "wine"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 求和np.sum(narray,axis)\n",
    "**axis=0对列求和，axis=1对行求和，不写则对所有元素求和**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 10.42298311,   5.63602251])"
      ]
     },
     "execution_count": 36,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#均值，每列的和除行数\n",
    "np.sum(wine,axis=0)/len(wine)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 用于布尔型数组的方法（记：布尔型数组在计算时True强制认为是1，False是0）\n",
    "**sum用来计算数组中True的个数，any用于测试数组中是否存在一个或多个True，而all则检查数组中所有值是\n",
    "否都是True，非布尔型数组对于any和all而言，非零元素为True**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 求均值np.mean(array,axis)\n",
    "axis同sum一样\n",
    "\n",
    "还有一些方法，如图\n",
    "<center>\n",
    "![](https://s1.ax1x.com/2018/01/27/pXT0Yj.png)    \n",
    "</center>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([ 10.42298311,   5.63602251])"
      ]
     },
     "execution_count": 38,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.mean(wine,axis=0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 求最大值np.max()，排序np.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "14.9"
      ]
     },
     "execution_count": 44,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#酒精最大14.9\n",
    "np.max(wine[:,0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([  8.4,   8.4,   8.5, ...,  14. ,  14. ,  14.9])"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#酒精排序\n",
    "np.sort(wine[:,0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 求数组中不重复数据np.unique()\n",
    "- 可选参数return_index，默认为false。返回元素出现的起始位置\n",
    "\n",
    "还有一些针对一维数组的集合运算函数\n",
    "![pXbuwT.png](https://s1.ax1x.com/2018/01/27/pXbuwT.png)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(array([ 3.,  4.,  5.,  6.,  7.,  8.]),\n",
       " array([459,  18,   0,   3,   7, 267], dtype=int64))"
      ]
     },
     "execution_count": 47,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#红酒评分有几种\n",
    "np.unique(wine[:,1],return_index=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "3.0"
      ]
     },
     "execution_count": 48,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "wine[459,1]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 122,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.20387906,  0.02382892, -0.06038605,  1.13040012],\n",
       "       [-1.37566748, -1.64353314, -1.63761698, -1.41485552],\n",
       "       [ 0.01813871,  0.35248472,  0.38183188, -1.35827553],\n",
       "       [ 0.10872247, -1.54797311, -0.939938  , -0.19239954],\n",
       "       [ 0.94904327, -0.76824475,  1.18742769,  0.27420587]])"
      ]
     },
     "execution_count": 122,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import numpy as np\n",
    "np.random.randn(5,4)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
